package zack.gateway.core.socket;

import zack.gateway.core.session.Configuration;
import zack.gateway.core.session.GatewaySessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zack.gateway.core.session.defaults.DefaultGatewaySessionFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**会话服务器
 * @author A1793
 */
public class GatewaySocketServer implements Callable<Channel> {

    private Logger logger = LoggerFactory.getLogger(GatewaySocketServer.class);
    private final Configuration configuration;
    private DefaultGatewaySessionFactory gatewaySessionFactory;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel channel;

    public GatewaySocketServer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }
    public void initEventLoopGroup() {
        bossGroup = new NioEventLoopGroup( configuration.getBossGroupSize());
        workerGroup = new NioEventLoopGroup( configuration.getWorkerGroupSize());
    }

    /**
     * 将会话服务启动放到线程中，不阻塞主线程
     * @return
     * @throws Exception
     */
    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = null;
        initEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new GatewayChannelInitializer(configuration,gatewaySessionFactory));


            channelFuture = bootstrap.bind(new InetSocketAddress(configuration.getPort())).syncUninterruptibly();
            channel = channelFuture.channel();
        }catch (Exception e){
            logger.error("socket server start error.", e);
        }finally{
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("socket server start done.");
            } else {
                logger.error("socket server start error.");
            }
        }
        return channel;
    }
}
